from typing import List

from fastapi import APIRouter
from models import *
from pydantic import BaseModel, field_validator

student = APIRouter()


@student.get("/")
async def get_all_student():
    # 1. 查询所有
    # students = await Student.all()
    # for stu in students:
    #     print(stu.name, stu.sn)

    # 2. 过滤查询
    # students = await Student.filter(name='rain')
    # students = await Student.filter(clas_id="2")
    # for stu in students:
    #     print(stu.name, stu.sn)

    # 3. 返回模型类型对象
    # stu = await Student.get(id=2)
    # print(stu.name, stu.sn)

    # 4. 模糊查询
    # students = await Student.filter(sn__gt=2001)
    # students = await Student.filter(id__range=[2,  2000])
    # students = await Student.filter(sn__in=[2001, 2002])
    # for stu in students:
    #     print(stu.name, stu.sn)

    # 5. values查询
    # students = await Student.all().values("name", "sn", "id")
    # print(students)

    # 6. 一对多查询 多对多查询
    alvin = await Student.get(name="alvin")
    print(alvin.name)
    print(alvin.sn)
    print(await alvin.clas.values("name"))
    print(await alvin.courses.all())
    print(await alvin.courses.all().values("name", "teacher__name"))
    students = await Student.all().values("name", "sn", "clas__name")
    return {
        "操作": students
    }


@student.get("/{id}")
async def get_student(id: int):
    return {
        "操作": "查看指定学生"
    }


class StudentIn(BaseModel):
    name: str
    pwd: str
    sn: int
    clas_id: int
    courses: List[int] = []

    @field_validator("name")
    def name_not_empty(cls, value):
        assert value.isalpha(), "姓名必须为字母"
        return value

    @field_validator("sn")
    def sn_not_empty(cls, value):
        assert value > 1000 and value < 10000, "学号必须在1000-10000之间"
        return value


@student.post("/")
async def add_student(student: StudentIn):
    # 插入到数据库
    # 方式一
    stu = Student(name=student.name, pwd=student.pwd, sn=student.sn, clas_id=student.clas_id)
    await stu.save()

    # 方式二：多对对关系绑定
    choose_course = await Course.filter(id__in=student.courses)
    await stu.courses.add(*choose_course)
    return {
        "操作": "添加学生"
    }


@student.put("/{id}")
async def update_student(id: int):
    return {
        "操作": "修改指定学生"
    }


@student.delete("/{id}")
async def delete_student(id: int):
    return {
        "操作": "删除指定学生"
    }
